package org.fangzz.cameramgr.cameramonitor.rest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.fangzz.cameramgr.cameramonitor.ApplicationConfig;
import org.fangzz.cameramgr.cameramonitor.dto.CameraSummary;
import org.fangzz.cameramgr.cameramonitor.dto.ResultCode;
import org.fangzz.cameramgr.cameramonitor.dto.StartLiveMonitorResponse;
import org.fangzz.cameramgr.cameramonitor.model.Camera;
import org.fangzz.cameramgr.cameramonitor.model.FfmpegProcess;
import org.fangzz.cameramgr.cameramonitor.service.CameraService;
import org.fangzz.cameramgr.cameramonitor.service.FfmpegProcessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 摄像头监控rest api
 * Created by cengruilin on 2018/6/7.
 */
@RestController
public class CameraMonitorRestController {
    private final static Log log = LogFactory.getLog(CameraMonitorRestController.class);

    @Autowired
    private ApplicationConfig applicationConfig;

    @Autowired
    private FfmpegProcessService ffmpegProcessService;

    @Autowired
    private CameraService cameraService;

    /**
     * 开始直播监控
     * @param cameraId 对应的摄像头ID
     * @return
     */
    @GetMapping("/api/monitors/live")
    public StartLiveMonitorResponse startLiveMonitor(Integer storeId, Integer cameraId, String resolution) {
        try {
            FfmpegProcess ffmpegProcess = ffmpegProcessService.startLiveConversion(storeId, cameraId, resolution);
            return StartLiveMonitorResponse.result(ffmpegProcess.getData(), ffmpegProcess.getPlayAddress(), ffmpegProcess.getMsg());
        } catch (Exception ex) {
            log.error("启动直播转换失败", ex);
            return StartLiveMonitorResponse.result(-1, ex.getMessage(), "启动直播转换失败");
        }
    }

    /**
     * 退出直播监控
     * @param cameraId
     */
    @DeleteMapping("/api/monitors/live/{cameraId}")
    public void exitLiveMonitor(@PathVariable Integer cameraId) {
        ffmpegProcessService.exitLiveMonitor(cameraId);
    }


    /**
     * 杀死第一个转码进程
     * @return
     */

    @DeleteMapping("/api/monitors/live/kill/{storeId}")
    public ResultCode killFirstThread(@PathVariable Integer storeId){
        try {
            boolean isKilled = ffmpegProcessService.killFirstFfmpegProcess(storeId);
            if (isKilled) {
                return ResultCode.result("进程结束成功","0",true);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultCode.error("转码进程不存在","1",true);
        }
        return ResultCode.result("进程结束失败","1",true);
    }

    /**
     * 查询直播进程是否被KILL
     */
    @GetMapping("/api/monitors/live/status/{cameraId}")
    public CameraSummary checkIsDeleted(@PathVariable Integer cameraId){
        Camera camera = cameraService.findById(cameraId);
        return CameraSummary.convert(camera);
    }


}